<?php
namespace app\common\repositories\member;
use app\common\repositories\BaseRepository;
use app\common\dao\member\MemberDao as dao;
use app\common\repositories\user\UserBalanceRepository;
use app\common\repositories\user\UserRepository;
use basic\services\MiniProgramService;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * @mixin dao
 */
class MemberRepository extends BaseRepository
{

    const MemberType = [
        0=> '普通用户',
        1=> '个人会员',
        2=> '企业会员',
    ];

    public function __construct(dao $dao)
    {
        $this->dao = $dao;
    }



    public function adminSetMember($uid,$memberId)
    {

        Db::transaction(function ()use($uid,$memberId){

            $user = app()->make(UserRepository::class)->get($uid);

            $member = $this->dao->getWhere(['member_id'=>$memberId,'id_del'=>0]);
            if(!$member){
                throw new ValidateException('套餐不存在');
            }


            if($member->type == 1){
                app()->make(UserRepository::class)->incrNumberField($uid,'integral',$member->count());
            }else{
                $user->save(['course_member'=>1]);
            }

            app()->make(MemberRecordRepository::class)->create(
                [
                    'order_sn'=>getOrderSn('M'),
                    'status'=>1,
                    'uid'=>0,
                    'to_uid'=>$uid,
                    'member_id'=>$memberId,
                    'member_title'=> "【后台开通】".$member->title,
                    'price'=>0
                ]
            );

        });
    }



    public function openMember($uid,$memberId){
        $member = $this->dao->get($memberId);
        /**@var $make MemberSettingRepository**/
        $make = app()->make(MemberSettingRepository::class);
        $memberType = $make->getUserMemberType($uid);

        $user = app()->make(UserRepository::class)->get($uid);

        if($memberType == 2 && $member->type == 1){
            throw new ValidateException('您已开通'.self::MemberType[$memberType].'!');
        }

        try {
            Db::startTrans();

            $order = app()->make(MemberRecordRepository::class)->create([
                'uid'=>$uid,
                'status'=>0,
                'price'=>$member->price,
                'member_id'=>$memberId,
                'type'=>$member->type,
                'order_no'=>getOrderSn('m'),
                'valid_time'=>$member['months']*30*24*3600,
            ]);

            if($member->price <= 0){
                $this->paySuccess($order->order_no);
                $payStatus = 0;
                $payConfig = [];
            } else if(input('pay_type') == 1){
                //余额支付
                $payStatus = 0;
                $payConfig = [];
                if($user->balance < $member->price){
                    throw new ValidateException('余额不足');
                }

                /**@var $balanceMake UserBalanceRepository**/
                $balanceMake = app()->make(UserBalanceRepository::class);
                $balanceMake->recordBalance($uid,0,'member','开通'.self::MemberType[$memberType],$member->price);

                $this->paySuccess($order->order_no);
            }else{
                $payStatus = 1;
                $payConfig = MiniProgramService::create()->jsPay($user->openid,$order['order_no'],$member->price*100,'开通'.self::MemberType[$memberType],'member');
            }

            Db::commit();
            return [
                'pay_status'=>$payStatus,
                'pay_config'=>$payConfig,
                'order_no'=>$order['order_no'],
                'price'=>$member->price
            ];
        }catch (\Exception $exception){
            Db::rollback();
            throw new ValidateException($exception->getMessage());
        }
    }


    public function paySuccess($orderNo){
        Db::transaction(function ()use ($orderNo){
            $order = app()->make(MemberRecordRepository::class)->getWhere(['order_no'=>$orderNo]);
            if($order->status != 0){
                return;
            }

            $order->save(['status'=>1]);
            $field = 'member_time'.($order->type == 2 ? '_2' : '');
            $user = app()->make(UserRepository::class)->get($order->uid);
            if($user->$field < time()){
               $user->save([$field=>time() + $order->valid_time]);
            }else{
                app()->make(UserRepository::class)->incrNumberField($order->uid,$field,$order->valid_time);
            }
            /**@var $balanceMake UserBalanceRepository**/
            $balanceMake = app()->make(UserBalanceRepository::class);
            $balanceMake->dealSpreadBrokerage($user->spread_uid,$order->record_id,'member');
        });
    }
}